package com.javaxiaobear.base.framework.security.service;

import cn.dev33.satoken.stp.StpUtil;
import com.javaxiaobear.base.common.utils.SecurityUtils;
import com.javaxiaobear.base.common.utils.ServletUtils;
import com.javaxiaobear.base.common.utils.StringUtils;
import com.javaxiaobear.base.common.utils.ip.AddressUtils;
import com.javaxiaobear.base.common.utils.ip.IpUtils;
import com.javaxiaobear.base.framework.security.LoginUser;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * token验证处理
 *
 * @author javaxiaobear
 */
@Component
@Slf4j
public class TokenService {

  /** 设置用户身份信息 */
  public void setLoginUser(LoginUser loginUser) {
    if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken())) {
      refreshToken(loginUser);
    }
  }

  /**
   * 刷新令牌有效期
   *
   * @param loginUser 登录信息
   */
  public void refreshToken(LoginUser loginUser) {
    loginUser.setLoginTime(System.currentTimeMillis());
    loginUser.setExpireTime(loginUser.getLoginTime() + StpUtil.getTokenInfo().getTokenTimeout());
    SecurityUtils.setLoginUser(loginUser);
  }

  /**
   * 设置用户代理信息
   *
   * @param loginUser 登录信息
   */
  public void setUserAgent(LoginUser loginUser) {
    UserAgent userAgent =
        UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
    String ip = IpUtils.getIpAddr();
    loginUser.setIpaddr(ip);
    loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
    loginUser.setBrowser(userAgent.getBrowser().getName());
    loginUser.setOs(userAgent.getOperatingSystem().getName());
  }
}
